<template>
  <div class="task-board">
    <div class="container">
      <h1>任务管理系统</h1>
      <div class="columns-container">
        <!-- 列容器 -->
        <div class="column" v-for="(column, columnIndex) in columns" :key="column.title">
          <div 
            class="column-header"
            draggable="true"
            @dragstart="onColumnHeaderDragStart($event, columnIndex)"
            @dragover.prevent="onDragOver($event, columnIndex)"
            @drop="onDrop($event, columnIndex, null)"
            @mousedown="handleColumnHeaderMouseDown"
            @mouseup="handleColumnHeaderMouseUp"
          >{{ column.title }} <span class="column-drag-indicator">⋮⋮</span></div>
          <div 
            class="tasks-container"
            @dragover.prevent="onDragOver($event, columnIndex)"
            @drop="onDrop($event, columnIndex, null)"
          >
            <!-- 任务卡片，支持拖拽 -->
            <div 
              class="card"
              v-for="(task, taskIndex) in column.tasks" 
              :key="task.id"
              draggable="true"
              :data-task-id="task.id"
              :data-column-index="columnIndex"
              @dragstart="onDragStart($event, columnIndex, taskIndex)"
              @dragover.prevent="onDragOver($event, columnIndex, taskIndex)"
              @dragleave="onDragLeave"
              @drop="onDrop($event, columnIndex, taskIndex)"
              @mousedown="handleCardMouseDown"
              @mouseup="handleCardMouseUp"
            >
              <!-- 确保卡片内所有元素都不会阻止拖拽行为 -->
              <p @dragstart.stop>{{ task.description }}</p>
              <div v-if="task.completed" class="priority-label priority-highest" @dragstart.stop>已完成</div>
              <div v-else-if="task.priority === 'Highest'" class="priority-label priority-highest" @dragstart.stop>Priority: Highest</div>
              <div v-else-if="task.priority === 'High'" class="priority-label priority-high" @dragstart.stop>Priority: High</div>
              <div v-else-if="task.status === 'In progress'" class="priority-label status-in-progress" @dragstart.stop>Status: In progress</div>
              <div v-else-if="task.status === 'To do'" class="priority-label status-to-do" @dragstart.stop>Status: To do</div>
              
              <!-- 拖拽指示器，提供更明显的拖拽提示 -->
              <div class="card-drag-handle">⋮⋮</div>
            </div>
            <!-- 占位元素，用于在列底部放置卡片 -->
            <div 
              class="drop-placeholder"
              :class="{ 'drag-over': dragOverColumn === columnIndex && dragOverTask === null }"
            ></div>
          </div>
          <div class="add-card-button" @click="addColumnCard(columnIndex)">+ 添加卡片</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';

// 定义任务和列的数据类型
interface Task {
  id: number;
  description: string;
  completed?: boolean;
  priority?: string;
  status?: string;
}

interface Column {
  title: string;
  tasks: Task[];
}

// 初始化任务数据
const columns = ref<Column[]>([
  {
    title: 'B. 养老系统优化改造',
    tasks: [
      { id: 1, description: '做样式设计', completed: true },
      { id: 2, description: '讨论任务给谁做？', priority: 'Highest' }
    ]
  },
  {
    title: '5. 抓娃娃机',
    tasks: [
      { id: 3, description: '需求分析', priority: 'High' },
      { id: 4, description: '需要和BA过一下细节', status: 'In progress' }
    ]
  },
  {
    title: '待处理任务',
    tasks: [
      { id: 5, description: '准备下周会议材料', status: 'To do' }
    ]
  }
]);

// 定义拖拽类型
type DragType = 'task' | 'column' | null;

// 拖拽状态
const dragState = reactive({
  sourceColumnIndex: -1,
  sourceTaskIndex: -1,
  task: null as Task | null,
  dragType: null as DragType
});

// 当前拖拽悬停位置
const dragOverColumn = ref<number | null>(null);
const dragOverTask = ref<number | null>(null);

// 添加新任务卡片的方法
function addColumnCard(columnIndex: number) {
  columns.value[columnIndex].tasks.push({
    id: Date.now(),
    description: '新任务',
    priority: '',
    status: ''
  });
}

// 拖拽开始
function onDragStart(event: DragEvent, columnIndex: number, taskIndex: number) {
  // 存储拖拽源信息
  dragState.sourceColumnIndex = columnIndex;
  dragState.sourceTaskIndex = taskIndex;
  dragState.task = columns.value[columnIndex].tasks[taskIndex];
  dragState.dragType = 'task';
  
  // 设置拖拽数据
  if (event.dataTransfer) {
    event.dataTransfer.setData('text/plain', JSON.stringify({
      columnIndex,
      taskIndex
    }));
    
    // 添加拖拽时的样式效果
    event.dataTransfer.effectAllowed = 'move';
    
    // 创建拖拽图像（可选，提升用户体验）
    const target = event.currentTarget as HTMLElement;
    if (target) {
      // 克隆目标元素作为拖拽图像
      const dragImage = target.cloneNode(true) as HTMLElement;
      dragImage.style.position = 'absolute';
      dragImage.style.top = '-1000px';
      dragImage.style.left = '-1000px';
      dragImage.style.width = target.offsetWidth + 'px';
      dragImage.style.opacity = '0.8';
      document.body.appendChild(dragImage);
      
      // 设置拖拽图像
      event.dataTransfer.setDragImage(dragImage, 20, 20);
      
      // 拖拽结束后清理
      setTimeout(() => {
        document.body.removeChild(dragImage);
      }, 0);
      
      // 设置原始元素透明度
      target.style.opacity = '0.4';
    }
  }
}

// 处理卡片鼠标按下事件
function handleCardMouseDown(event: MouseEvent) {
  const target = event.currentTarget as HTMLElement;
  target.classList.add('card-dragging');
}

// 处理列头拖拽开始
function onColumnHeaderDragStart(event: DragEvent, columnIndex: number) {
  // 存储拖拽源信息
  dragState.sourceColumnIndex = columnIndex;
  dragState.dragType = 'column';
  
  // 设置拖拽数据
  if (event.dataTransfer) {
    event.dataTransfer.setData('text/plain', JSON.stringify({
      columnIndex,
      dragType: 'column'
    }));
    
    // 添加拖拽时的样式效果
    event.dataTransfer.effectAllowed = 'move';
    
    // 创建拖拽图像（可选，提升用户体验）
    const target = event.currentTarget as HTMLElement;
    if (target) {
      // 克隆目标元素作为拖拽图像
      const dragImage = target.cloneNode(true) as HTMLElement;
      dragImage.style.position = 'absolute';
      dragImage.style.top = '-1000px';
      dragImage.style.left = '-1000px';
      dragImage.style.width = target.offsetWidth + 'px';
      dragImage.style.opacity = '0.8';
      document.body.appendChild(dragImage);
      
      // 设置拖拽图像
      event.dataTransfer.setDragImage(dragImage, 20, 20);
      
      // 拖拽结束后清理
      setTimeout(() => {
        document.body.removeChild(dragImage);
      }, 0);
      
      // 设置原始元素透明度
      target.style.opacity = '0.4';
    }
  }
}

// 处理卡片鼠标松开事件
function handleCardMouseUp(event: MouseEvent) {
  const target = event.currentTarget as HTMLElement;
  target.classList.remove('card-dragging');
}

// 处理列头鼠标按下事件
function handleColumnHeaderMouseDown(event: MouseEvent) {
  const target = event.currentTarget as HTMLElement;
  target.classList.add('column-header-dragging');
  
  const columnElement = target.parentElement;
  if (columnElement) {
    columnElement.classList.add('column-dragging');
  }
}

// 处理列头鼠标松开事件
function handleColumnHeaderMouseUp(event: MouseEvent) {
  const target = event.currentTarget as HTMLElement;
  target.classList.remove('column-header-dragging');
  
  const columnElement = target.parentElement;
  if (columnElement) {
    columnElement.classList.remove('column-dragging');
  }
}

// 拖拽经过目标区域
function onDragOver(event: DragEvent, columnIndex: number, taskIndex: number | null = null) {
  event.preventDefault();
  if (event.dataTransfer) {
    event.dataTransfer.dropEffect = 'move';
  }
  
  // 更新拖拽悬停状态
  dragOverColumn.value = columnIndex;
  dragOverTask.value = taskIndex;
}

// 拖拽离开目标区域
function onDragLeave() {
  dragOverColumn.value = null;
  dragOverTask.value = null;
}

// 放置卡片
function onDrop(event: DragEvent, targetColumnIndex: number, targetTaskIndex: number | null) {
  event.preventDefault();
  
  // 重置拖拽样式
  const cards = document.querySelectorAll('.card');
  cards.forEach(card => {
    (card as HTMLElement).style.opacity = '1';
  });
  
  // 获取拖拽源信息
  const sourceData = dragState;
  
  // 检查是否是有效的拖拽操作
  if (sourceData.sourceColumnIndex === -1) {
    return;
  }
  
  // 根据拖拽类型进行不同处理
  if (sourceData.dragType === 'task' && sourceData.task) {
    // 任务拖拽处理
    // 从源位置移除任务
    const sourceColumn = columns.value[sourceData.sourceColumnIndex];
    sourceColumn.tasks.splice(sourceData.sourceTaskIndex, 1);
    
    // 计算目标位置
    let insertIndex = 0;
    const targetColumn = columns.value[targetColumnIndex];
    
    if (targetTaskIndex === null) {
      // 拖放到列底部
      insertIndex = targetColumn.tasks.length;
    } else {
      // 拖放到卡片前/后
      // 如果是从同一列拖拽，需要调整插入位置
      if (sourceData.sourceColumnIndex === targetColumnIndex) {
        insertIndex = sourceData.sourceTaskIndex < targetTaskIndex ? targetTaskIndex : targetTaskIndex;
      } else {
        insertIndex = targetTaskIndex;
      }
    }
    
    // 插入任务到目标位置
    targetColumn.tasks.splice(insertIndex, 0, sourceData.task);
  } else if (sourceData.dragType === 'column') {
    // 列拖拽处理
    if (sourceData.sourceColumnIndex !== targetColumnIndex) {
      // 从源位置移除列
      const sourceColumn = columns.value.splice(sourceData.sourceColumnIndex, 1)[0];
      
      // 插入列到目标位置
      columns.value.splice(targetColumnIndex, 0, sourceColumn);
    }
  }
  
  // 重置拖拽状态
  dragState.sourceColumnIndex = -1;
  dragState.sourceTaskIndex = -1;
  dragState.task = null;
  dragState.dragType = null;
  dragOverColumn.value = null;
  dragOverTask.value = null;
}
</script>

<style scoped>
.task-board {
  background: linear-gradient(90deg, #6a5acd, #8e44ad);
  min-height: 100vh;
  padding: 2rem;
  color: white;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
}

h1 {
  text-align: center;
  margin-bottom: 2rem;
  font-size: 2.5rem;
}

.columns-container {
  display: flex;
  gap: 2rem;
  flex-wrap: wrap;
}

.column {
  background: #f5f5f5;
  border-radius: 8px;
  width: 250px;
  min-height: 300px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.column:hover {
  transform: translateY(-2px);
}

.column-header {
  background: #1a237e;
  color: white;
  padding: 1rem;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  font-size: 1.2rem;
  font-weight: bold;
  cursor: grab;
  transition: background-color 0.2s ease;
  position: relative;
  user-select: none;
}

.column-header:hover {
  background: #283593;
}

.column-header.dragging {
  opacity: 0.5;
  cursor: grabbing;
}

/* 列拖拽指示器 */
.column-drag-indicator {
  position: absolute;
  right: 1rem;
  font-size: 12px;
  opacity: 0.7;
  cursor: grab;
}

.column-header:hover .column-drag-indicator {
  opacity: 1;
}

/* 列拖拽时的样式 */
.column.dragging {
  opacity: 0.5;
}

/* 列之间的拖拽占位符 */
.columns-container {
  display: flex;
  gap: 1rem;
  position: relative;
}

.tasks-container {
  padding: 1rem;
  min-height: 250px;
  position: relative;
}

/* 拖拽占位符 */
.drop-placeholder {
  height: 10px;
  margin: 0 0 1rem 0;
  transition: background-color 0.2s ease;
}

.drop-placeholder.drag-over {
  background-color: rgba(26, 35, 126, 0.2);
  height: 20px;
  border-radius: 4px;
}

.card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 1rem;
  padding: 1rem;
  cursor: grab;
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
}

/* 拖拽时的样式 */
.card.dragging {
  opacity: 0.5;
  transform: rotate(2deg);
}

.card.card-dragging {
  cursor: grabbing;
}

/* 拖拽指示器样式 */
.card-drag-handle {
  position: absolute;
  top: 8px;
  right: 8px;
  color: #a0aec0;
  font-size: 12px;
  cursor: grab;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.card:hover .card-drag-handle {
  opacity: 1;
}

.card.card-dragging .card-drag-handle {
  cursor: grabbing;
}

.card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-1px);
}

.card:active {
  cursor: grabbing;
}

.card:hover:not([draggable="false"]) {
  border: 1px dashed #1a237e;
}

/* 拖拽经过时的样式 */
.card.drag-over {
  border-top: 2px solid #1a237e;
  margin-bottom: 0;
}

.card.drag-over + .card {
  margin-top: 1rem;
}

.card p {
  margin: 0 0 0.5rem 0;
  color: #333;
}

.priority-label {
  display: inline-block;
  padding: 0.2rem 0.5rem;
  border-radius: 4px;
  font-size: 0.8rem;
}

.priority-highest {
  background-color: red;
  color: white;
}

.priority-high {
  background-color: orange;
  color: black;
}

.status-in-progress {
  background-color: blue;
  color: white;
}

.status-to-do {
  background-color: orange;
  color: black;
}

.add-card-button {
  color: #666;
  cursor: pointer;
  text-align: center;
  padding: 0.5rem;
  font-size: 0.9rem;
  border-top: 1px solid #ddd;
  transition: background-color 0.2s ease;
}

.add-card-button:hover {
  background-color: #e9e9e9;
}
</style>
